<!-- 企业管理 -->
<template>
  <!-- 搜索区域 -->
  <el-form inline :model="searchForm" class="search-form">
    <el-form-item label="企业名称">
      <el-autocomplete style="width: 250px" v-model="searchForm.enterpriseName" placeholder="请输入企业名称"
        :fetch-suggestions="queryEnterprise" :trigger-on-focus="false" clearable @select="handleSelectEnterprise" />
    </el-form-item>
    <el-form-item label="所属园区">
      <el-select v-model="searchForm.parkId" placeholder="请选择园区" @change="handleSelectParkIdChange" clearable
        style="width: 200px">
        <el-option v-for="park in parkData" :key="park.id" :label="park.name" :value="park.id"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="所属楼栋">
      <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" @change="handleSelectBuildIdChange" clearable
        style="width: 200px">
        <el-option v-for="building in parkBuildingData" :key="building.id" :label="building.name"
          :value="building.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属楼层">
      <el-select v-model="searchForm.floor" placeholder="请选择楼栋" @change="handleSelectRoomIdChange" clearable
        style="width: 200px">
        <el-option v-for="room in roomData" :key="room" :label="room" :value="room"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="入住状态">
      <el-select v-model="searchForm.selectedValue" placeholder="请选择入住状态" @change="handleSelectChange" clearable
        style="width: 200px;">
        <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="是否关注">
      <el-select v-model="searchForm.isFollowed" placeholder="请选择关注状态" @change="handleSelectFollowedChange" clearable
        style="width: 200px">
        <el-option v-for="park in optionsisFollowed" :key="park.value" :label="park.label"
          :value="park.value"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAddEnterprise">
        新增企业
      </el-button>
    </el-form-item>
  </el-form>

  <!-- 企业列表 -->
  <el-table :data="enterpriseData" :border="true" style="width: 100%" highlight-current-row>
    <el-table-column prop="enterpriseName" label="企业名称" :align="center" min-width="200">
      <template #default="scope">
        <div class="enterprise-name">
          {{ scope.row.enterpriseName }}
          <el-tag v-if="scope.row.enterpriseIsFollowed" size="small" type="success">
            关注
          </el-tag>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="所属园区" :align="center" min-width="110">
      <template #default="scope">
        {{ scope.row.parkInfo?.name || '无数据' }}
      </template>
    </el-table-column>
    <!-- <el-table-column label="楼栋" :align="center" width="110">
      <template #default="scope">
        <el-tag class="mr-2">
          {{ scope.row.parkBuilding?.name || '无数据' }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column label="楼层/房间" :align="center" width="110">
      <template #default="scope">
        <el-tag v-for="(room, index) in scope.row.enterpriseRoomPojos || []" :key="index" type="success" size="small"
          class="mr-2">
          {{ room.parkRoom.floor }}层-{{ room.parkRoom.roomNumber }}
        </el-tag>
        <el-tag v-if="!scope.row.enterpriseRoomPojos || scope.row.enterpriseRoomPojos.length === 0">
          无数据
        </el-tag>
      </template>
    </el-table-column> -->

    <el-table-column prop="enterpriseIndustry" label="所属行业" :align="center" width="100">
      <template #default="scope">
        <span v-if="!scope.row.enterpriseIndustry" />
        <el-tag v-if="scope.row.enterpriseIndustry">
          {{
            scope.row.enterpriseIndustry === 'information_technology' ? '信息技术' :
              scope.row.enterpriseIndustry === 'financial_services' ? '金融服务' :
                scope.row.enterpriseIndustry === 'manufacturing' ? '制造业' :
                  scope.row.enterpriseIndustry === 'healthcare' ? '医疗健康' :
                    scope.row.enterpriseIndustry === 'education' ? '教育培训' :
                      scope.row.enterpriseIndustry === 'culture_media' ? '文化传媒' :
                        scope.row.enterpriseIndustry === 'retail_trade' ? '零售贸易' :
                          scope.row.enterpriseIndustry === 'logistics' ? '物流运输' :
                            scope.row.enterpriseIndustry === 'catering_accommodation' ? '餐饮住宿' : '其他'
          }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="enterpriseType" label="企业类型" :align="center" width="120">
      <template #default="scope">
        <span v-if="!scope.row.enterpriseType" />
        <el-tag v-if="scope.row.enterpriseType">
          {{
            scope.row.enterpriseType === 'limited_liability_company' ? '有限责任公司' :
              scope.row.enterpriseType === 'joint_stock_company' ? '股份有限公司' :
                scope.row.enterpriseType === 'sole_proprietorship' ? '个人独资企业' :
                  scope.row.enterpriseType === 'partnership' ? '合伙企业' :
                    scope.row.enterpriseType === 'state_owned' ? '国有企业' :
                      scope.row.enterpriseType === 'foreign_owned' ? '外资企业' : '其他'
          }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="enterpriseStatus" label="入驻状态" width="100" :align="center">
      <template #default="scope">
        <el-tag :type="statusTypeMap[scope.row.enterpriseStatus].type"
          :effect="statusTypeMap[scope.row.enterpriseStatus].effect">
          {{ statusTypeMap[scope.row.enterpriseStatus].label }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="enterpriseContactPerson" label="联系人" :align="center" width="120"></el-table-column>
    <el-table-column prop="enterpriseContactPhone" label="联系电话" :align="center" width="120"></el-table-column>
    <el-table-column label="操作" width="220" :align="center" fixed="right">
      <template #default="scope">
        <el-button size="small" @click="handleView(scope.row)">
          查看
        </el-button>
        <el-button size="small" type="primary" @click="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button size="small" :type="scope.row.isFollowed ? 'default' : 'success'" @click="handleFollow(scope.row)">
          {{ scope.row.enterpriseIsFollowed ? '取消关注' : '关注' }}
        </el-button>
        <el-dropdown size="small" @command="(command) => handleStatusChange(scope.row, command)">
          <el-button text type="warning">
            状态修改
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="pending">审核中</el-dropdown-item>
              <el-dropdown-item command="approved">已入驻</el-dropdown-item>
              <el-dropdown-item command="moved_out">已离园</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页（可选） -->
  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.currentPage"
    :page-sizes="[10, 20, 50]" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper"
    :total="page.total" />


  <!-- 企业表单组件 -->
  <EnterpriseForm :visible="formVisible" :enterprise="currentEnterprise" :parkData="parkData" @close="handleFormClose"
    @save="handleFormSave" />

    <!-- 查看弹框 -->
  <EnterpriseViewPage :visible="viewPageVisible" :enterprise="currentEnterprise" @close="handleViewPageClose" />
</template>
<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import request from '@/api/request'
import { EnterpriseConstants } from '../../enterprise/constant/EnterpriseConstant'
import { ElMessage, ElLoading } from 'element-plus';
import EnterpriseForm from '../from/EnterpriseForm.vue';//表单页面 
import EnterpriseViewPage from '../viewpage/EnterpriseViewPage.vue';

defineEmits(['callUpdateLoadAnalysisMethod']);
// 获取组件实例（用于 emit 事件）
const { emit } = getCurrentInstance();

const props = defineProps({
  parkData: {
    type: Object,
    default: () => ([])
  }
});
const enterpriseData = ref([]);
const parkData = props.parkData;
const roomData = ref([]);
//楼栋筛选下拉框
const parkBuildingData = ref([])
const center = 'center'
// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 1
})

// 是否关注选项数据
const optionsisFollowed = EnterpriseConstants.optionsisFollowed;
// 审核状态选项数据
const optionsStatus = EnterpriseConstants.optionsStatus;
// 审核状态显示类型映射
const statusTypeMap = EnterpriseConstants.statusTypeMap;

// 初始化数据
onMounted(() => {
  //加载企业数据表格
  loadEnterpriseData()
});

// 搜索表单
const searchForm = ref({
  enterpriseName: null,
  parkId: null,
  selectedValue: null,
  isFollowed: null,
  buildingId: null,
  floor: null
})

//加载企业数据表格
const loadEnterpriseData = async () => {
  // const loading = ElLoading.service({
  //   lock: true,
  //   text: '正在初始化页面数据...',
  //   background: 'rgba(0, 0, 0, 0.7)',
  // })
  try {
    const resData = await request.get('/enterprise/getEnterprisePage', {
      params: {
        pageNum: page.value.current,
        pageSize: page.value.size,
        enterpriseName: searchForm.value.enterpriseName,
        parkId: searchForm.value.parkId,
        buildingId: searchForm.value.buildingId,
        floor: searchForm.value.floor,
        enterpriseStatus: searchForm.value.selectedValue,
        enterpriseIsFollowed: searchForm.value.isFollowed
      }
    })
    if (resData.success) {
      enterpriseData.value = resData.data.list
      page.value.total = resData.data.total
    }
  } catch (err) {

  } finally {
    // loading.close()
  }
}
//重置搜索表单
const resetSearch = () => {
  searchForm.value = {}
  roomData.value = []
  //楼栋筛选下拉框
  parkBuildingData.value = []
  loadEnterpriseData()
};

// 搜索按钮逻辑
const handleSearch = () => {
  loadEnterpriseData()
}


// 表单相关状态
const formVisible = ref(false);
const currentEnterprise = ref(null);


// 新增企业
const handleAddEnterprise = () => {
  currentEnterprise.value = null; // 清空当前企业数据
  formVisible.value = true; // 显示表单
};

const handleEdit = (row) => {
  currentEnterprise.value = JSON.parse(JSON.stringify(row));
  formVisible.value = true; // 显示表单
}

// 关闭表单
const handleFormClose = () => {
  formVisible.value = false;
  currentEnterprise.value = null;
};

// 保存表单数据（新增或编辑）
const handleFormSave = async (formData) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在操作...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    let url = 'enterprise/add'
    if (formData.enterpriseId) {
      // 编辑操作
      url = 'enterprise/modify'
    }
    // formData.parkInfo={}
    // formData.parkBuilding={}

    const opt = await request.post(url, formData)
    if (opt.success) {
      ElMessage.success(opt.message)
      // 关闭表单并刷新列表
      formVisible.value = false;
      currentEnterprise.value = null;
      loadEnterpriseData();
      emit('callUpdateLoadAnalysisMethod');
    } else {
      ElMessage.error(opt.message)
    }
  } catch (error) {
    ElMessage.error('保存失败，请重试');
  } finally {
    loading.close()
  }
}


// 处理园区选中变化
const handleSelectParkIdChange = (value) => {
  searchForm.value.buildingId = null
  searchForm.value.floor = null
  if (value) {
    loadEnterpriseData()
    //查询楼栋信息
    getBuildIngInfo(value)
  } else {
    loadEnterpriseData()
    roomData.value = []
    //楼栋筛选下拉框
    parkBuildingData.value = []
  }
};
//查询楼栋信息
const getBuildIngInfo = async (value) => {
  const data = await request.get("park-building/getParkBuildingByEnterpriseId", {
    params: {
      enterpriseId: value
    }
  })
  if (data.success) {
    parkBuildingData.value = data.data
  }
}
//楼栋选择
const handleSelectBuildIdChange = (value) => {
  searchForm.value.floor = null
  if (value) {
    loadEnterpriseData()
    //查询楼层
    getParkRoom(value)
  } else {
    roomData.value = []
    loadEnterpriseData()
  }

}
//查询楼层
const getParkRoom = async (value) => {
  const data = await request.get("parkRoom/getParkFloorByBuildindId", {
    params: {
      buildingId: value
    }
  })
  if (data.success) {
    roomData.value = data.data
  }
}
//楼层选择
const handleSelectRoomIdChange = (value) => {
  loadEnterpriseData()
}

// 处理选中变化
const handleSelectChange = (value) => {
  loadEnterpriseData()
};
// 处理选中变化
const handleSelectFollowedChange = (value) => {
  loadEnterpriseData()
};
// 分页-每页条数改变
const handleSizeChange = (val) => {
  page.value.size = val
  loadEnterpriseData()
}

// 分页-当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  loadEnterpriseData()
}


const viewPageVisible = ref(false)

//查看
const handleView = (row) => {
  viewPageVisible.value = true
  currentEnterprise.value = JSON.parse(JSON.stringify(row));
}

const handleViewPageClose = () => {
  viewPageVisible.value = false;
  currentEnterprise.value = null;
}

//关注
const handleFollow = (row) => {
  try {
    request.get('enterprise/modifyIsFollowed', {
      params: {
        enterpriseId: row.enterpriseId,
        enterpriseIsFollowed: !row.enterpriseIsFollowed
      }
    }).then(res => {
      if (res.success) {
        // 2. 直接更新表格中目标行的状态（不重新查询全表）
        const targetIndex = enterpriseData.value.findIndex(item => item.enterpriseId === row.enterpriseId);
        if (targetIndex > -1) {
          // 深拷贝避免直接修改响应式数据的引用
          enterpriseData.value[targetIndex] = {
            ...enterpriseData.value[targetIndex],
            enterpriseIsFollowed: !row.enterpriseIsFollowed // 更新状态字段
          };
        }
      } else {
        ElMessage.error(res.message);
      }
    })
  } catch (err) {
    ElMessage.error('操作失败，请重试');
  }
}
//状态修改
const handleStatusChange = (row, command) => {
  try {
    if (command != row.enterpriseStatus) {
      request.get('enterprise/modifyStatus', {
        params: {
          enterpriseId: row.enterpriseId,
          status: command
        }
      }).then(res => {
        if (res.success) {
          loadEnterpriseData();
          emit('callUpdateLoadAnalysisMethod');
        } else {
          ElMessage.error(res.message);
        }
      })
    } else {
      ElMessage.info('修改相同');
    }
  } catch (err) {
    ElMessage.error('操作失败，请重试');
  }
}

const searchTimer = ref(null)  // 防抖计时器（ref 用于响应式存储）

/**
 * 输入时触发：请求后端接口获取匹配的企业列表
 * @param {string} queryString - 当前输入内容
 * @param {Function} callback - 回传下拉数据的回调
 */
const queryEnterprise = (queryString, callback) => {
  // 清除上一次的定时器（防抖）
  clearTimeout(searchTimer.value)

  // 300ms 防抖：输入停止后再请求
  searchTimer.value = setTimeout(async () => {
    // 输入为空时不请求
    if (!queryString.trim()) {
      callback([])
      return
    }
    try {
      const res = await request.get("enterprise/getEnterpriseName", {
        params: { enterpriseName: queryString }  // 传递搜索关键词
      })
      if (res.success) {
        if (res.data.length == 0) {
          callback([])
          return
        }
        // 格式化数据：下拉框需要 { value: '显示文本', ...其他字段 } 结构
        const suggestions = res.data.map(enterprise => ({
          value: enterprise.enterpriseName,  // 下拉框中显示的企业名称
          id: enterprise.enterpriseId,       // 企业ID（可选，用于后续业务）
          // 可添加其他需要的字段（如地址、代码等）
        }));

        // 将数据回传给下拉框
        callback(suggestions)
      } else {
        callback([])  // 出错时返回空数组
      }

    } catch (error) {
      console.error('获取企业列表失败：', error)
      callback([])  // 出错时返回空数组
    }
  }, 300)
}

/**
 * 选中下拉项时触发
 * @param {Object} item - 选中的企业对象（包含 value、id 等字段）
 */
const handleSelectEnterprise = (item) => {
  console.log('选中的企业：', item)
  searchForm.enterpriseName = item.value
  loadEnterpriseData()
}
</script>
<style scoped>
.search-form {
  margin-bottom: 16px;
  text-align: left;
}
</style>